<template>
  <div class="directory-grid">
    <!-- 顶部标题和操作区域 -->
    <div class="directory-header">
      <h2><el-icon class="header-icon"><Collection /></el-icon>Agent MCP Directory</h2>
      <div class="directory-actions">
        <el-button type="warning" @click="handleBulkImport" class="action-button">
          <el-icon><Upload /></el-icon>GitHub导入
        </el-button>

        <el-button type="success" @click="handleAddProject" class="action-button">
          <el-icon><Plus /></el-icon>手动添加
        </el-button>
      </div>
    </div>

    <!-- MCP 工具导航区域 -->
    <div class="mcp-navigation">
      <el-card class="navigation-card">
        <template #header>
          <div class="navigation-header">
            <el-icon><Link /></el-icon>
            <span>MCP 工具常用导航</span>
          </div>
        </template>
        <div class="navigation-links">
          <el-link 
            href="https://mcp.so/" 
            target="_blank" 
            type="primary"
            class="nav-link"
          >
            <el-icon><Link /></el-icon>
            mcp.so
          </el-link>
          <el-link 
            href="https://github.com/punkpeye/awesome-mcp-servers" 
            target="_blank" 
            type="success"
            class="nav-link"
          >
            <el-icon><Star /></el-icon>
            awesome-mcp-servers
          </el-link>
          <el-link 
            href="https://modelscope.cn/mcp" 
            target="_blank" 
            type="warning"
            class="nav-link"
          >
            <el-icon><Cloudy /></el-icon>
            阿里魔搭MCP社区
          </el-link>
        </div>
      </el-card>
    </div>
    
    <!-- 筛选区域 -->
    <div class="filter-container">
      <el-input
        v-model="searchQuery"
        placeholder="搜索项目..."
        clearable
        class="search-input"
        @input="filterAgents"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <!-- 将筛选条件放在搜索框下方 -->
      <div class="filters">
        <div class="filter-label"><el-icon><Compass /></el-icon> 筛选：</div>
        <el-select
          v-model="languageFilter"
          placeholder="编程语言"
          clearable
          class="filter-select"
          @change="filterAgents"
        >
          <el-option
            v-for="lang in availableLanguages"
            :key="lang"
            :label="lang"
            :value="lang"
          />
        </el-select>
        
        <el-select
          v-model="tagFilter"
          placeholder="标签"
          clearable
          class="filter-select"
          @change="filterAgents"
        >
          <el-option
            v-for="tag in availableTags"
            :key="tag"
            :label="tag"
            :value="tag"
          />
        </el-select>
        
        <el-select
          v-model="sortOption"
          placeholder="排序方式"
          class="filter-select"
          @change="filterAgents"
        >
          <el-option label="热门程度" value="stars" />
          <el-option label="最近更新" value="lastUpdated" />
          <el-option label="名称(A-Z)" value="nameAsc" />
          <el-option label="名称(Z-A)" value="nameDesc" />
        </el-select>
      </div>
      <!-- 刷新和计数区域 -->
      <div class="filter-section">
        <el-button type="primary" size="small" @click="refreshData" :loading="isRefreshing" class="refresh-button">
          <el-icon><RefreshRight /></el-icon>
          刷新数据
        </el-button>
        
        <div class="count-display">
          <el-icon class="count-icon"><Files /></el-icon>
          <span v-if="filteredAgents.length > 0">
            显示 {{ filteredAgents.length }} 个项目
          </span>
          <span v-else>
            未找到匹配项目
          </span>
        </div>
      </div>
    </div>
    
    <!-- 列表视图内容保持不变 -->
    <div class="directory-content">
      <div v-if="filteredAgents.length === 0" class="empty-directory">
        <el-icon class="text-4xl mb-4 text-purple-400"><Warning /></el-icon>
        <p class="text-xl">未找到匹配项目</p>
        <p class="mt-2">尝试使用不同的搜索条件或清除筛选器</p>
      </div>
      
      <div v-else class="agent-grid">
        <div 
          v-for="agent in paginatedAgents" 
          :key="agent.id"
          class="agent-card"
        >
          <div class="agent-card-header">
            <!-- 第一行：star和集成标签 -->
            <div class="header-top-row">
              <div class="agent-icon">
                <el-icon><Star /></el-icon>
              </div>
              <el-tag v-if="isIntegratedToAIWeb(agent)" type="success" size="small" class="integration-tag">
                <el-icon class="mr-1"><Connection /></el-icon>AIWeb已集成
              </el-tag>
              <el-dropdown trigger="click" @command="handleCommand($event, agent)" @click.stop>
                <span class="more-actions">
                  <el-icon><More /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="copy">集成参数配置</el-dropdown-item>
                    <el-dropdown-item :command="isIntegratedToAIWeb(agent) ? 'removeFromWeb' : 'integrateWeb'">
                      <span class="flex items-center">
                        <el-icon v-if="isIntegratedToAIWeb(agent)" class="mr-1 text-green-500"><Check /></el-icon>
                        {{ isIntegratedToAIWeb(agent) ? '从 AIWeb 移除' : '集成到 AIWeb' }}
                      </span>
                    </el-dropdown-item>
                    <el-dropdown-item command="integrateCursor">集成到 Cursor</el-dropdown-item>
                    <el-dropdown-item command="integrateTrae">集成到 Trae</el-dropdown-item>
                    <el-dropdown-item command="delete">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            
            <!-- 第二行：名称和更多按钮 -->
            <div class="header-bottom-row">
              <h3 class="agent-name" @click="openGitHubUrl(agent.githubUrl)">
                {{ agent.name }}
                <el-icon v-if="agent.isVerified" class="verified-icon"><Check /></el-icon>
              </h3>
            </div>
          </div>
          
          <div class="agent-card-content">
            <div class="mb-2 flex items-center justify-between">
              <el-tag size="small" class="language-tag">{{ agent.language }}</el-tag>
            </div>
            <p class="agent-description">{{ agent.description }}</p>
            
            <div class="agent-tags">
              <el-tag 
                v-for="tag in agent.tags.slice(0, 3)" 
                :key="tag" 
                type="info" 
                size="small"
                class="tag-item"
              >
                {{ tag }}
              </el-tag>
              <span v-if="agent.tags.length > 3" class="more-tags">+{{ agent.tags.length - 3 }}</span>
            </div>
          </div>
          
          <div class="agent-card-footer">
            <div class="flex items-center justify-between w-full">
              <span class="update-date">更新于: {{ formatDate(agent.lastUpdated) }}</span>
              <span class="stars-count">
                <el-icon><Star /></el-icon>
                {{ formatStars(agent.stars) }}
              </span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页控件 -->
      <div v-if="filteredAgents.length > 0" class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 48, 96]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredAgents.length"
          background
          class="custom-pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 添加项目模态框 -->
    <AddProjectModalComponent
      v-model:visible="addProjectModalVisible"
      @project-added="handleProjectAdded"
    />
    
    <!-- 批量导入模态框 -->
    <BulkImportModalComponent
      v-model:visible="bulkImportModalVisible"
      @projects-added="handleProjectsAdded"
    />
    
    <!-- 添加模态对话框 -->
    <el-dialog
      v-model="jsonDialogVisible"
      title="MCP工具配置"
      width="60%"
      :before-close="handleDialogClose"
    >
      <div class="mb-4 config-help">
        <el-alert
          title="配置格式说明"
          type="info"
          :description="configHelpText"
          :closable="false"
          show-icon
        />
      </div>
      <el-input
        type="textarea"
        v-model="jsonContent"
        :rows="10"
        placeholder="请输入有效的JSON数据"
      ></el-input>
      <span v-if="jsonError" class="error-message">{{ jsonError }}</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="jsonDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveJsonContent" :loading="saveLoading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useMcpApiService } from '../../services/McpApiService'
import AddProjectModalComponent from './AddProjectModalComponent.vue'
import BulkImportModalComponent from './BulkImportModalComponent.vue'
import { ElMessage } from 'element-plus'
import { Search, Plus, Upload, Star, Timer, Grid, Menu, Check, Warning, Link, More, CopyDocument, Connection, Download, RefreshRight, Collection, Files, Compass, Cloudy } from '@element-plus/icons-vue'

/**
 * Agent代表一个MCP代理项目
 */
interface Agent {
  /**
   * 唯一标识符
   */
  id: string;
  
  /**
   * 代理名称
   */
  name: string;
  
  /**
   * 代理描述
   */
  description: string;
  
  /**
   * GitHub URL
   */
  githubUrl: string;
  
  /**
   * 编程语言
   */
  language: string;
  
  /**
   * 标签数组
   */
  tags: string[];
  
  /**
   * 星标数
   */
  stars: number;
  
  /**
   * 最后更新时间
   */
  lastUpdated: string;
  
  /**
   * 是否已验证
   */
  isVerified?: boolean;
}

/**
 * 代理工具配置接口
 */
interface AgentToolConfig {
  /**
   * 配置ID
   */
  id: string;
  
  /**
   * 工具名称
   */
  name: string;
  
  /**
   * 工具描述
   */
  description?: string;
  
  /**
   * 执行命令
   */
  command: string;
  
  /**
   * 命令参数数组
   */
  args?: string[];
  
  /**
   * MCP服务器配置
   */
  mcpServers?: Record<string, {
    command: string;
    args?: string[];
  }>;
}

// 组件属性
const props = defineProps<{
  initialSearchQuery?: string
}>()

// 服务引用
const mcpApiService = useMcpApiService()

// 状态管理
const agents = ref<Agent[]>([])
const loading = ref(true)
const searchQuery = ref(props.initialSearchQuery || '')
const languageFilter = ref('')
const tagFilter = ref('')
const sortOption = ref('stars')
const viewMode = ref('grid')
const currentPage = ref(1)
const pageSize = ref(12)
const addProjectModalVisible = ref(false)
const bulkImportModalVisible = ref(false)
const integrationModalVisible = ref(false)
const selectedAgent = ref<Agent | null>(null)
const currentAgent = ref<Agent | null>(null)
const isRefreshing = ref(false)
const jsonDialogVisible = ref(false)
const jsonContent = ref('')
const jsonError = ref('')
const saveLoading = ref(false)
const integratedToolIds = ref<string[]>([])

// 计算属性
const availableLanguages = computed(() => {
  const languages = new Set<string>()
  agents.value.forEach((agent: Agent) => {
    if (agent.language) {
      languages.add(agent.language)
    }
  })
  return Array.from(languages).sort()
})

const availableTags = computed(() => {
  const tags = new Set<string>()
  agents.value.forEach((agent: Agent) => {
    agent.tags?.forEach((tag: string) => {
      tags.add(tag)
    })
  })
  return Array.from(tags).sort()
})

const filteredAgents = computed(() => {
  let result = [...agents.value]
  
  // 应用搜索查询
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(agent => 
      agent.name.toLowerCase().includes(query) || 
      agent.description.toLowerCase().includes(query)
    )
  }
  
  // 应用语言筛选
  if (languageFilter.value) {
    result = result.filter(agent => 
      agent.language === languageFilter.value
    )
  }
  
  // 应用标签筛选
  if (tagFilter.value) {
    result = result.filter(agent => 
      agent.tags?.includes(tagFilter.value)
    )
  }
  
  // 应用排序
  switch (sortOption.value) {
    case 'stars':
      result.sort((a, b) => b.stars - a.stars)
      break
    case 'lastUpdated':
      result.sort((a, b) => new Date(b.lastUpdated).getTime() - new Date(a.lastUpdated).getTime())
      break
    case 'nameAsc':
      result.sort((a, b) => a.name.localeCompare(b.name))
      break
    case 'nameDesc':
      result.sort((a, b) => b.name.localeCompare(a.name))
      break
  }
  
  return result
})

const paginatedAgents = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredAgents.value.slice(start, end)
})

const configHelpText = computed(() => {
  if (currentAgent.value) {
    return `可访问项目文档 ${currentAgent.value.githubUrl} 获取详细信息。`
  }
  return '请根据项目文档进行参数配置。'
})

// 生命周期钩子
onMounted(async () => {
  try {
    agents.value = await mcpApiService.getAllProjects()
    loading.value = false
    
    // 获取AIWeb集成状态
    await refreshAIWebIntegrationStatus()
  } catch (error) {
    console.error('加载项目失败:', error)
    ElMessage.error('无法加载项目列表，请稍后再试')
    agents.value = []
    loading.value = false
  }
})

// 监听属性变化
watch(() => props.initialSearchQuery, (newVal) => {
  if (newVal !== undefined) {
    searchQuery.value = newVal
    filterAgents()
  }
})

// 方法
const filterAgents = () => {
  currentPage.value = 1
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

const formatStars = (stars: number): string => {
  if (stars >= 1000) {
    return (stars / 1000).toFixed(1) + 'k'
  }
  return stars.toString()
}

const formatDate = (dateString: string): string => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric'
  })
}

const openGitHubUrl = (url: string) => {
  window.open(url, '_blank')
}

// 添加的功能：打开添加项目模态框
const handleAddProject = () => {
  addProjectModalVisible.value = true
}

// 添加的功能：打开批量导入模态框
const handleBulkImport = () => {
  bulkImportModalVisible.value = true
}

// 添加的功能：处理项目添加成功
const handleProjectAdded = (count: number) => {
  refreshProjects()
  ElMessage.success(`已成功添加 ${count} 个项目`)
}

// 添加的功能：处理批量项目添加成功
const handleProjectsAdded = (addedProjects: any[]) => {
  refreshProjects()
  ElMessage.success(`已成功添加 ${addedProjects.length} 个项目`)
}

// 添加的功能：刷新项目列表
const refreshProjects = async () => {
  loading.value = true
  try {
    agents.value = await mcpApiService.refreshAgentData()
  } catch (error) {
    console.error('刷新项目列表失败:', error)
    ElMessage.error('刷新项目列表失败')
  } finally {
    loading.value = false
  }
}

// 集成相关方法
const integrateWithCursor = (agent: Agent | null) => {
  if (!agent) return
  ElMessage.success(`已将 ${agent.name} 集成到 Cursor`)
  integrationModalVisible.value = false
}

const integrateWithTrae = (agent: Agent | null) => {
  if (!agent) return
  ElMessage.success(`已将 ${agent.name} 集成到 Trae`)
  integrationModalVisible.value = false
}

const cloneRepository = (agent: Agent | null) => {
  if (!agent) return
  const gitCloneCmd = `git clone ${agent.githubUrl}`
  navigator.clipboard.writeText(gitCloneCmd)
  ElMessage.success('Git克隆命令已复制到剪贴板')
  integrationModalVisible.value = false
}

const copyInstallCommand = (agent: Agent | null) => {
  if (!agent) return
  // 根据项目语言生成不同的安装命令
  let installCmd = ''
  
  switch (agent.language.toLowerCase()) {
    case 'python':
      installCmd = `pip install -e git+${agent.githubUrl}.git#egg=${agent.name.toLowerCase()}`
      break
    case 'javascript':
    case 'typescript':
      installCmd = `npm install ${agent.githubUrl}`
      break
    case 'go':
      installCmd = `go get ${agent.githubUrl.replace('https://github.com/', '')}`
      break
    default:
      installCmd = `git clone ${agent.githubUrl}`
  }
  
  navigator.clipboard.writeText(installCmd)
  ElMessage.success('安装命令已复制到剪贴板')
  integrationModalVisible.value = false
}

// 获取所有工具配置
const fetchToolConfigs = async (): Promise<AgentToolConfig[]> => {
  try {
    // 先尝试从本地缓存获取
    const cacheKey = 'mcp_tool_configs';
    const cachedConfigs = localStorage.getItem(cacheKey);
    if (cachedConfigs) {
      return JSON.parse(cachedConfigs);
    }
    
    // 从API获取
    const response = await fetch('/api/mcpTool/tool-configs');
    if (!response.ok) {
      throw new Error(`获取配置失败: ${response.status}`);
    }
    
    const configs = await response.json();
    
    // 缓存结果
    localStorage.setItem(cacheKey, JSON.stringify(configs));
    
    return configs;
  } catch (error) {
    console.error('获取工具配置失败:', error);
    ElMessage.error('获取工具配置失败，将使用默认模板');
    return [];
  }
}

// 根据ID获取工具配置
const fetchToolConfigById = async (id: string): Promise<AgentToolConfig | null> => {
  try {
    // 先尝试从本地缓存获取所有配置
    const configs = await fetchToolConfigs();
    const cachedConfig = configs.find(config => config.id === id);
    if (cachedConfig) {
      return cachedConfig;
    }
    
    // 从API获取特定配置
    const response = await fetch(`/api/mcpTool/tool-config/${id}`);
    if (!response.ok) {
      if (response.status === 404) {
        return null; // 配置不存在
      }
      throw new Error(`获取配置失败: ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    console.error(`获取工具配置 ${id} 失败:`, error);
    return null;
  }
}

// 修改handleCommand方法
const handleCommand = (command: string, agent: Agent) => {
  if (command === 'integrateWeb') {
    // 集成到 AIWeb
    integrateWithAIWeb(agent)
  } else if (command === 'removeFromWeb') {
    // 从 AIWeb 移除
    removeFromAIWeb(agent)
  } else if (command === 'integrateCursor') {
    integrateWithCursor(agent)
  } else if (command === 'integrateTrae') {
    integrateWithTrae(agent)
  } else if (command === 'delete') {
    // 调用后端删除项目
    mcpApiService.deleteProject(agent.id)
      .then(() => {
        ElMessage.success('删除成功')
        refreshProjects()
      })
      .catch(() => {
        ElMessage.error('删除失败')
      })
  } else if (command === 'copy') {
    // 设置当前操作的agent
    currentAgent.value = agent
    
    // 显示JSON输入对话框
    jsonDialogVisible.value = true
    jsonContent.value = ''
    jsonError.value = ''
    saveLoading.value = true
    
    // 尝试获取已有配置
    fetchToolConfigs().then(configs => {
      saveLoading.value = false
      
      // 搜索与当前agent名称相关的配置
      const agentName = agent.name.toLowerCase()
      const matchingConfig = configs.find((config: AgentToolConfig) => 
        config.name.toLowerCase().includes(agentName) || 
        (config.description && config.description.toLowerCase().includes(agentName))
      )
  

      if (matchingConfig) {
        // 找到匹配的配置，自动填充
        jsonContent.value = JSON.stringify(matchingConfig, null, 2)
        ElMessage.info('已找到相关配置并自动填充')
      } else {
        // 未找到匹配配置，创建一个默认模板
        const timestamp = new Date().getTime()
        const randomSuffix = Math.floor(Math.random() * 1000)
        
        // 根据代理语言生成合适的默认命令
        let defaultCommand = "uvx"
        let defaultArgs: string[] = [agent.name.toLowerCase().replace(/[^a-z0-9]/g, '_')]
        
    
        const defaultTemplate: AgentToolConfig = {
          id: "mcp-" + agent.id,
          name: agent.name,
          description: agent.description || `${agent.name} 的MCP工具配置`,
          command: defaultCommand,
          args: defaultArgs
        }
        
        jsonContent.value = JSON.stringify(defaultTemplate, null, 2)
        ElMessage.info('已创建基于当前项目的配置模板，请填写命令和参数')
      }
    }).catch(error => {
      saveLoading.value = false
      console.error('获取配置失败:', error)
      ElMessage.error('获取配置失败，请手动填写')
      
      // 发生错误时也创建模板
      const timestamp = new Date().getTime()
      const defaultTemplate: AgentToolConfig = {
        id: `mcp-${timestamp}`,
        name: agent.name,
        description: agent.description,
        command: "",
        args: []
      }
      
      jsonContent.value = JSON.stringify(defaultTemplate, null, 2)
    })
  }
}

const validateJson = () => {
  try {
    if (!jsonContent.value.trim()) {
      jsonError.value = '内容不能为空'
      return false
    }
    
    const jsonData = JSON.parse(jsonContent.value)
    
    // 检查输入的格式
    if (jsonData.mcpServers) {
      // 检查mcpServers对象
      if (Object.keys(jsonData.mcpServers).length === 0) {
        jsonError.value = 'mcpServers对象为空'
        return false
      }
      
      // 检查第一个服务
      const serverKey = Object.keys(jsonData.mcpServers)[0]
      const server = jsonData.mcpServers[serverKey]
      
      if (!server.command) {
        jsonError.value = `服务 "${serverKey}" 缺少command字段`
        return false
      }
    } else {
      // 检查标准格式
      if (!jsonData.id || !jsonData.name || !jsonData.command) {
        jsonError.value = '配置缺少必要字段 (id, name, command)'
        return false
      }
    }
    
    jsonError.value = ''
    return true
  } catch (error: any) {
    jsonError.value = `JSON格式错误: ${error.message}`
    return false
  }
}

// 修改saveJsonContent方法
const saveJsonContent = async () => {
  if (!validateJson()) {
    return
  }
  
  saveLoading.value = true
  
  try {
    // 解析JSON内容
    const configData = JSON.parse(jsonContent.value)
    
    // 确保必要字段存在
    if (!configData.command || configData.command.trim() === '') {
      jsonError.value = '命令字段不能为空'
      saveLoading.value = false
      return
    }
    
    // 发送到后端API
    const response = await fetch('/api/mcpTool/save-tool-config', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        config: configData
      })
    })
    
    if (!response.ok) {
      throw new Error(`服务器响应错误: ${response.status}`)
    }
    
    const result = await response.json()
    
    if (result.status === 'success') {
      ElMessage.success('MCP工具配置保存成功')
      jsonDialogVisible.value = false
      
      // 刷新数据
      refreshData()
    } else {
      ElMessage.error(`保存失败: ${result.message || '未知错误'}`)
    }
  } catch (error: any) {
    console.error('保存MCP工具配置时出错:', error)
    ElMessage.error(`保存失败: ${error.message || '未知错误'}`)
  } finally {
    saveLoading.value = false
  }
}

const refreshData = async () => {
  isRefreshing.value = true
  try {
    // 刷新项目数据
    await refreshProjects()
    
    // 清除本地配置缓存（如果有）
    const cacheKey = 'mcp_tool_configs'
    if (localStorage.getItem(cacheKey)) {
      localStorage.removeItem(cacheKey)
    }
    
    // 通知用户刷新成功
    ElMessage.success('数据已成功刷新')
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('刷新数据失败，请检查网络连接')
  } finally {
    isRefreshing.value = false
  }
}

const handleDialogClose = () => {
  jsonDialogVisible.value = false
  jsonContent.value = ''
  jsonError.value = ''
}

// 新增方法：集成到AIWeb
const integrateWithAIWeb = async (agent: Agent) => {
  try {
    // 准备要添加到commonTools的工具配置
    const toolConfig = {
      id: `mcp-${agent.id}`,
      name: agent.name.toLowerCase().replace(/[^a-z0-9]/g, '-'),
      description: agent.description || `${agent.name} 的MCP工具配置`,
      command: "vux",
      args: [agent.name.toLowerCase().replace(/[^a-z0-9]/g, '_')]
    };
    
    // 调用后端接口添加工具
    const response = await fetch('/api/common/tools/MCPTools', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(toolConfig)
    });
    
    if (!response.ok) {
      throw new Error(`服务器响应错误: ${response.status}`);
    }
    
    const result = await response.json();
    
    // 更新集成状态
    await refreshAIWebIntegrationStatus();
    
    ElMessage.success(`已将 ${agent.name} 集成到 AIWeb`);
  } catch (error: any) {
    console.error('集成到AIWeb失败:', error);
    ElMessage.error(`集成失败: ${error.message || '未知错误'}`);
  }
}

// 检查AIWeb集成状态
const refreshAIWebIntegrationStatus = async () => {
  try {
    const response = await fetch('/api/common/tools/list')
    if (!response.ok) {
      throw new Error(`获取工具列表失败: ${response.status}`)
    }
    
    const data = await response.json()
    if (data && data.MCPTools && Array.isArray(data.MCPTools)) {
      // 提取已集成工具的ID
      integratedToolIds.value = data.MCPTools.map((tool: any) => {
        // 从ID中提取agent ID部分
        const idMatch = tool.id.match(/mcp-(.*)/);
        return idMatch ? idMatch[1] : tool.id;
      });
    } else if (data && data.mcpTools && Array.isArray(data.mcpTools)) {
      // 兼容小写情况
      integratedToolIds.value = data.mcpTools.map((tool: any) => {
        const idMatch = tool.id.match(/mcp-(.*)/);
        return idMatch ? idMatch[1] : tool.id;
      });
    } else {
      // 清空集成ID列表
      integratedToolIds.value = [];
    }
  } catch (error) {
    console.error('获取AIWeb集成状态失败:', error)
    integratedToolIds.value = [];
  }
}

// 检查agent是否已集成到AIWeb
const isIntegratedToAIWeb = (agent: Agent): boolean => {
  return integratedToolIds.value.includes(agent.id)
}

// 新增方法：从AIWeb移除
const removeFromAIWeb = async (agent: Agent) => {
  try {
    const toolId = `mcp-${agent.id}`;
    
    // 调用删除接口
    const response = await fetch(`/api/common/tools/MCPTools/${toolId}`, {
      method: 'DELETE'
    });
    
    if (!response.ok) {
      throw new Error(`服务器响应错误: ${response.status}`);
    }
    
    // 更新集成状态
    await refreshAIWebIntegrationStatus();
    
    ElMessage.success(`已从 AIWeb 移除 ${agent.name}`);
  } catch (error: any) {
    console.error('从AIWeb移除失败:', error);
    ElMessage.error(`移除失败: ${error.message || '未知错误'}`);
  }
}
</script>

<style scoped>
.directory-grid {
  height: 100%;
  padding: 1.5rem;
  display: flex;
  flex-direction: column;
  color: #f3f4f6;
}

.directory-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  padding-bottom: 1.5rem;
  border-bottom: 1px solid #374151;
  background: linear-gradient(to right, rgba(31, 41, 55, 0.7), rgba(17, 24, 39, 0.7));
  padding: 1.5rem;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.directory-header h2 {
  margin: 0;
  font-size: 1.75rem;
  background: linear-gradient(to right, #e5e7eb, #a78bfa);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.header-icon {
  font-size: 1.5rem;
  color: #8B5CF6;
  margin-right: 0.5rem;
}

.directory-actions {
  display: flex;
  gap: 1rem;
}

.search-input {
  width: 100%;
  max-width: 400px;
}

.search-input:focus-within {
  transform: translateY(-2px);
}

.search-input :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.1);
  background: rgba(31, 41, 55, 0.6);
  border-radius: 6px;
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px rgba(168, 85, 247, 0.5);
}

.search-input :deep(.el-input__inner) {
  color: #d1d5db;
}

.action-button {
  transition: all 0.3s ease;
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.filter-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
  margin-bottom: 2rem;
  padding: 1rem;
  background: rgba(31, 41, 55, 0.8);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.filter-section {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.refresh-button {
  background: linear-gradient(to right, #6366F1, #8B5CF6);
  border: none;
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  transition: all 0.3s ease;
  height: 36px;
}

.refresh-button:hover {
  background: linear-gradient(to right, #4F46E5, #7C3AED);
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(99, 102, 241, 0.4);
}

.filter-label {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  color: #d1d5db;
  font-weight: 500;
  white-space: nowrap;
}

.count-display {
  background-color: rgba(31, 41, 55, 0.8);
  padding: 0.5rem 1rem;
  border-radius: 6px;
  border: 1px solid #4B5563;
  color: #d1d5db;
  font-size: 0.95rem;
  font-weight: 500;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.2);
  display: flex;
  align-items: center;
  gap: 0.4rem;
}

.count-icon {
  color: #8B5CF6;
  font-size: 1.1rem;
}

.filters {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  gap: 0.75rem;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

.filter-select {
  min-width: 120px;
}

.filter-select :deep(.el-input__wrapper) {
  background: rgba(31, 41, 55, 0.6);
  box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.1);
  border-radius: 6px;
}

.filter-select :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px rgba(168, 85, 247, 0.5);
}

.filter-select :deep(.el-input__inner) {
  color: #d1d5db;
}

.directory-content {
  flex: 1;
  overflow-y: auto;
  padding: 0.5rem 0;
}

.empty-directory {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  background-color: #1f2937;
  border-radius: 8px;
  border: 1px solid #374151;
  color: #9ca3af;
}

.agent-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 2rem;
}

.agent-card {
  background: linear-gradient(to bottom, #1f2937, #111827);
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
  transition: all 0.3s ease;
  overflow: visible;
  min-height: 280px;
  cursor: pointer;
  border-top: 3px solid #6366F1;
  border: 1px solid #374151;
}

.agent-card:hover {
  transform: translateY(-7px) scale(1.02);
  box-shadow: 0 12px 20px rgba(0, 0, 0, 0.4);
  border-color: #8B5CF6;
}

.agent-card-header {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  padding: 1.25rem;
  background: linear-gradient(to right, #1f2937, #111827);
  border-bottom: 1px solid rgba(55, 65, 81, 0.5);
}

.header-top-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  gap: 0.75rem;
}

.header-bottom-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.agent-name {
  font-size: 1.2rem;
  color: #e5e7eb;
  font-weight: 600;
  margin: 0;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 0.25rem;
  transition: color 0.3s;
}

.agent-name:hover {
  color: #a78bfa;
}

.mr-1 {
  margin-right: 0.25rem;
}

.more-actions {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border-radius: 4px;
  cursor: pointer;
  color: #9ca3af;
  margin-left: auto;
}

.more-actions:hover {
  background-color: rgba(255, 255, 255, 0.1);
  color: #a78bfa;
}

.agent-icon {
  width: 42px;
  height: 42px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #6366F1 0%, #8B5CF6 100%);
  color: white;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(99, 102, 241, 0.3);
}

.agent-icon .el-icon {
  font-size: 1.4rem;
}

.agent-card-content {
  flex: 1;
  padding: 1rem 1.25rem;
  overflow: visible;
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.language-tag {
  background-color: rgba(55, 65, 81, 0.8);
  border: none;
  color: #e5e7eb;
  font-size: 0.8rem;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  display: inline-block;
}

.integration-tag {
  display: flex;
  align-items: center;
  font-size: 0.8rem;
  padding: 0.15rem 0.6rem;
  height: 24px;
  line-height: 24px;
  background: linear-gradient(135deg, #10B981, #059669);
  color: white;
  border: none;
  border-radius: 4px;
  box-shadow: 0 2px 6px rgba(16, 185, 129, 0.3);
}

.agent-description {
  display: block;
  white-space: normal;
  overflow: visible;
  line-height: 1.5;
}

.agent-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  margin-top: auto;
}

.tag-item {
  background-color: rgba(55, 65, 81, 0.6);
  border: none;
  font-size: 0.8rem;
  padding: 0.15rem 0.6rem;
  height: 24px;
  line-height: 24px;
  border-radius: 4px;
  color: #d1d5db;
}

.more-tags {
  font-size: 0.8rem;
  color: #9ca3af;
  padding: 0.15rem 0;
}

.agent-card-footer {
  padding: 0.85rem 1.25rem;
  background-color: rgba(17, 24, 39, 0.8);
  font-size: 0.85rem;
  color: #9ca3af;
  border-top: 1px solid rgba(55, 65, 81, 0.5);
  display: flex;
  justify-content: space-between;
}

.update-date {
  font-size: 0.85rem;
  color: #d1d5db;
}

.stars-count {
  display: flex;
  align-items: center;
  color: #fbbf24;
  gap: 0.4rem;
  font-weight: 500;
}

.verified-icon {
  margin-left: 0;
  color: #a78bfa;
}

.pagination-container {
  margin-top: 2.5rem;
  display: flex;
  justify-content: center;
  padding: 1rem;
  background: linear-gradient(to bottom, rgba(31, 41, 55, 0.7), rgba(17, 24, 39, 0.7));
  border-radius: 10px;
  border: 1px solid rgba(55, 65, 81, 0.5);
}

.custom-pagination {
  --el-pagination-bg-color: transparent;
  --el-pagination-hover-color: #a78bfa;
  --el-pagination-button-color: #d1d5db;
  --el-pagination-button-bg-color: rgba(55, 65, 81, 0.8);
  --el-pagination-button-disabled-color: #9ca3af;
  --el-pagination-button-disabled-bg-color: rgba(31, 41, 55, 0.5);
  --el-pagination-border-radius: 6px;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background: linear-gradient(to right, #6366F1, #8B5CF6);
  box-shadow: 0 2px 8px rgba(99, 102, 241, 0.4);
}

:deep(.el-pagination.is-background .btn-prev),
:deep(.el-pagination.is-background .btn-next),
:deep(.el-pagination.is-background .el-pager li) {
  color: #e5e7eb;
  background-color: rgba(55, 65, 81, 0.6);
  border: 1px solid rgba(75, 85, 99, 0.4);
  margin: 0 2px;
}

:deep(.el-pagination.is-background .btn-prev:hover),
:deep(.el-pagination.is-background .btn-next:hover),
:deep(.el-pagination.is-background .el-pager li:hover) {
  color: #a78bfa;
  background-color: rgba(55, 65, 81, 0.8);
}

/* 对话框样式 */
:deep(.el-dialog) {
  background: linear-gradient(135deg, #1f2937, #111827);
  border-radius: 12px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.4);
  border: 1px solid rgba(55, 65, 81, 0.6);
  backdrop-filter: blur(10px);
}

:deep(.el-dialog__title) {
  color: #e5e7eb;
}

:deep(.el-dialog__body) {
  color: #d1d5db;
  padding: 20px 30px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #374151;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #374151;
}

.error-message {
  color: red;
  font-size: 14px;
  margin-top: 5px;
  display: block;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .directory-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }
  
  .directory-actions {
    width: 100%;
    flex-direction: column;
  }
  
  .search-input,
  .filters,
  .filter-section {
    width: 100%;
    flex-direction: column;
    align-items: flex-start;
  }
  
  .agent-grid {
    grid-template-columns: 1fr;
  }
}

.mcp-navigation {
  margin: 1.5rem 0;
  padding: 0 0.5rem;
}

.navigation-card {
  background: linear-gradient(to right, rgba(31, 41, 55, 0.7), rgba(17, 24, 39, 0.7));
  border: 1px solid rgba(55, 65, 81, 0.5);
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(10px);
}

.navigation-header {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1.1rem;
  font-weight: 500;
  color: #e5e7eb;
  padding: 0.75rem 1rem;
  border-bottom: 1px solid rgba(55, 65, 81, 0.5);
}

.navigation-header .el-icon {
  color: #8B5CF6;
  font-size: 1.2rem;
}

.navigation-links {
  display: flex;
  flex-direction: row;
  gap: 1rem;
  padding: 1rem;
  flex-wrap: wrap;
}

.nav-link {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1.25rem;
  border-radius: 6px;
  transition: all 0.3s ease;
  background: rgba(31, 41, 55, 0.5);
  border: 1px solid rgba(55, 65, 81, 0.3);
  flex: 1;
  min-width: 200px;
  justify-content: center;
}

.nav-link:hover {
  background: rgba(31, 41, 55, 0.8);
  transform: translateY(-2px);
  border-color: #8B5CF6;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .navigation-links {
    flex-direction: column;
    gap: 0.75rem;
  }
  
  .nav-link {
    width: 100%;
    min-width: unset;
  }
}
</style>